<?php
/**
 * RuiZhiKaiYuan公用curl类
 * 检测短信接口状态
 * @author duqibing
 * @since 2013-3-21 
 */
class Curl {
	/**
	 * @todo curl post请求方式
	 */
	function curl_post($url, array $post = NULL, array $options = array()) {
	    $defaults = array( 
	        CURLOPT_POST => 1, 
	        CURLOPT_HEADER => 0, 
	        CURLOPT_URL => $url, 
	        CURLOPT_FRESH_CONNECT => 1, 
	        CURLOPT_RETURNTRANSFER => 1, 
	        CURLOPT_FORBID_REUSE => 1, 
	        CURLOPT_TIMEOUT => 4, 
	        CURLOPT_POSTFIELDS => http_build_query($post) 
	    ); 
	    
	    $ch = curl_init(); 
	    curl_setopt_array($ch, ($options + $defaults)); 
	    if( ! $result = curl_exec($ch)) {
	    	//错误处理
	    	$curl_errno = curl_errno($ch);
	    	$this->writeErrLog("CURL--POST接口调用异常,url:$url.'--'.$curl_errno:\n" ,  APP_ROOT .'/#Logs/Interfaces/'.date('Y-m-d').'.txt');
	    }
	    
	    $post_result = rawurldecode(implode('|',$post));
	    $this->writeErrLog("CURL--POST接口调用成功,url:$url.'--'.Post:$post_result\n" , APP_ROOT .'/#Logs/Interfaces/'.date('Y-m-d').'.txt');
	    curl_close($ch); 
	    return $result; 
	}
	
	/**
	 * @todo 写错误日志
	 * @param unknown_type $errorMes
	 * @param unknown_type $file_name 如 _TMP_PATH_.'log/'.date('Y-m-d').'.txt'
	 */
	public function writeErrLog($errorMes, $file_name = "") {
		if(empty($errorMes)) {
			return false;
		}
		//目录不存在就创建
		if (!file_exists (dirname($file_name))) {
		  if (!@mkdir (dirname($file_name), 0777)) {
		        die($file_name."目录创建失败！");
		  }
		}
		$msg = date('Y-m-d H:i:s').' >>> '.$errorMes."\r\n";
		file_put_contents($file_name,$msg,FILE_APPEND);
	}

    /**
     * @param $url
     * @param array $post
     * @param array $options
     * @return mixed
     */
    function curlPost($url, array $post = NULL, array $options = array()) {
        $defaults = array(
            CURLOPT_POST => 1,
            CURLOPT_HEADER => 0,
            CURLOPT_URL => $url,
            CURLOPT_FRESH_CONNECT => 1,
            CURLOPT_RETURNTRANSFER => 1,
            CURLOPT_FORBID_REUSE => 1,
            CURLOPT_TIMEOUT => 4,
            CURLOPT_POSTFIELDS => http_build_query($post)
        );
        $ch = curl_init();
        curl_setopt_array($ch, ($options + $defaults));
        if (!$result = curl_exec($ch)) {
            trigger_error(curl_error($ch));
        }
        curl_close($ch);
        return $result;
    }





}